package com.woupla.produit;

import java.util.List;
import java.util.Map;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.jboss.seam.transaction.Transactional;
import org.jboss.solder.logging.Logger;
import org.primefaces.model.SortOrder;

import com.woupla.model.Company;
import com.woupla.model.Companyproduit;

@Stateless
public class CompanyProductEJB {
	@Inject
	private Logger log;

	@Inject
	private EntityManager em;

	public List<Companyproduit> findSortedFiltringProduct(Company company, int first, int pageSize, String sortField, SortOrder sortOrder,
			Map<String, String> filters) {
		String queryString = "SELECT c FROM Companyproduit c WHERE c.company = " + company.getId();
		String filterString = "";
		for (Map.Entry<String, String> filter : filters.entrySet()) {
			filterString = " AND " + filter.getKey() + " LIKE '%" + filter.getValue() +"%'";
		}
		if (filterString != null)
			queryString = queryString + filterString;
		if (sortField != null){
			if(sortOrder == SortOrder.ASCENDING)
				queryString =  queryString + " ORDER BY " + sortField + " ASC";
			else
				queryString =  queryString + " ORDER BY " + sortField + " DESC";
		}
			
		
		TypedQuery<Companyproduit> query = em.createQuery(queryString, Companyproduit.class);
		query.setFirstResult(first);
		query.setMaxResults(pageSize);
		List<Companyproduit> produits = query.getResultList();
		return produits;

	}
	
	@Transactional
	public void createProduct(Companyproduit companyproduit){
		em.persist(companyproduit);
	}
	public int countAllProduitToCompany(Company company){
		Query query =  em.createNamedQuery("Companyproduit.CountForCompany");
		query.setParameter("company", company.getId());
		int count = ((Long) query.getSingleResult()).intValue();
		return count;
	}

}
